package com.qf.service.impl;

import com.qf.mapper.RoleMapper;
import com.qf.pojo.Role;
import com.qf.service.RoleService;
import com.qf.utils.ResultMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.transform.Result;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleMapper roleMapper;

    @Override
    public ResultMsg queryAllRole(Integer page, Integer limit) {
        if (page != null) page = page <= 1 ? 1 : page;
        List<Role> roles = roleMapper.queryAllRoles(page == null ? null : ((page - 1) * limit), limit);
        if (roles.size() == 0) return ResultMsg.FAILED(201, "no data was found");
        ResultMsg success = ResultMsg.SUCCESS(0, roles, roleMapper.queryRoleCount().getRoleId());
        return success;
    }

    @Override
    public ResultMsg queryOneRole(Integer roleId) {
        if (roleId == null) return ResultMsg.FAILED(202, "roleId can not be null");
        List<Role> roles = roleMapper.queryRole(roleId);
        if (roles.size() != 1) return ResultMsg.FAILED(201, "no data was found");
        return ResultMsg.SUCCESS(roles.get(0));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultMsg updateRole(Role role) {
        if (role.getRoleId() == null) return ResultMsg.FAILED(202, "parameter 'roleId' can not be null");
        if (role.getPermissionId() == null) return ResultMsg.FAILED(203, "parameter 'permissionId' can not be null");
        try {
            Integer i = roleMapper.updateRole(role);
            if (i != 1) return ResultMsg.FAILED(201, "Failed to modify data");
            return ResultMsg.SUCCESS(role);
        } catch (Exception e) {
            return ResultMsg.FAILED(204, e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMsg insertRole(Role role) {
        if (role.getPermissionId() == null) return ResultMsg.FAILED(203, "parameter 'permissionId can not be null");
        role.setRoleId(null);
        try {
            Integer res = roleMapper.insertRole(role);
            if (res != 1) return ResultMsg.FAILED(201, "Failed to insert data");
            return ResultMsg.SUCCESS(role);
        } catch (Exception e) {
            return ResultMsg.FAILED(204, e.getMessage());
        }

    }
}
